/**
 * Created by Luji on 2017/02/03.
 */
import serFormTemp from '../form/serviceForm.html';
import serFormCtrl from '../form/serviceForm.ctrl.js';

class Create {
    constructor(detail,appSrv,ctgNotification, $stateParams,$timeout,$uiModal,$state,$window) {
        "ngInject";
        this._appSrv       = appSrv;
        this._notification = ctgNotification;
        this.$stateParams  = $stateParams;
        this.$timeout      = $timeout;
        this._uiModal      = $uiModal;
        this._state        = $state;
        this.detail        = detail;
        this.chartChange   = false;
        this.treeData      = [];

        $timeout(()=> {
            angular.element('.graph-chart').css({
                'height': ($window.innerHeight - 260) + 'px'
            });
            this.model().resize();
        }, 0, false);

        this.init();
    }
    init(){
        this.config = {
            tooltip:{
                trigger: 'item',
                formatter: function (params) {
                    return params.name
                }
            },
            series : [
                {
                    type: 'graph',
                    symbolSize: 50,
                    label: {
                        normal: {
                            show: true,
                            formatter:function(data){
                                if(data.name.length>5){
                                    return data.name.substr(0, 5)+'..'
                                }else{
                                    return data.name
                                }

                            }
                        }
                    },
                    itemStyle :{
                        normal : {
                            width : '10px'
                        }
                    },
                    data: [],
                    links: [],
                    lineStyle: {
                        normal: {
                            opacity: 1
                        }
                    }
                }
            ]
        };

        if (this.detail) {
            this.chartEmpty = false;
            this.edit       = true;
            this.name       = this.detail.name;
            this.treeData   = JSON.parse(this.detail.descJson);
            this.rootNode   = this.treeData[0];
            this.bulidTree(this.treeData);
        }else{
            this.chartEmpty = true;
            this.edit       = false;
            this.config.series[0].data = [{"name":"选择依赖","x":0,"y":0}];
        }

        //chart init完
        this.$timeout( ()=>{
            //事件绑定

            this.model().on('click', (params)=> {
                if(params.dataType == 'node'){
                    this.openForm(params.name,false,params);
                }

            })
        }, 0, false);


    }


    openForm(souceName,editRootNode,params){
        this._uiModal.open({
            templateUrl: serFormTemp,
            controller: serFormCtrl,
            controllerAs: 'vm',
            size:'lg',
            resolve: {
                treeData : () => {
                    return this.treeData
                },
                souceName: () => {
                    return souceName
                },
                editRootNode : () =>{
                    return editRootNode;
                }
            }
        }).result.then((data)=> {
            this.chartEmpty  = false;
            this.chartChange = true;
            function findByName(nodes){
                angular.forEach(nodes, (ele,index)=>{
                    if(ele.name == params.name){
                        if(data.addNodes && data.addNodes.length!=0){
                            angular.forEach(data.addNodes, (name,index)=>{
                                ele.children.push({name:name,children:[]})
                            })
                        }

                        if(data.delNodes && data.delNodes.length!=0){
                            angular.forEach(data.delNodes, (name,index)=>{
                                angular.forEach(ele.children,(child,cIndex)=>{
                                    if(child.name==name){
                                        ele.children.splice(cIndex,1)
                                    }
                                })
                            })
                        }

                    }else{
                        findByName(ele.children)
                    }
                })
            }
            if(data.rootNode){
                this.treeData[0].name = data.rootNode
            }else{
                if(this.treeData.length == 0){
                    this.treeData = [{name:data.addNodes[0],children:[],x:1,y:1}];
                }else{
                    findByName(this.treeData)
                }
            }


            this.bulidTree(this.treeData);
        });
    }


    save(){

        this._appSrv.saveSerDep(this.$stateParams.id?this.$stateParams.id:'',this.name,JSON.stringify(this.treeData), this.filter).then(data=> {
            if(this.edit){
                this._notification.success('修改'+this.name+'成功.');
            }else{
                this._notification.success('创建服务依赖成功.');
            }
            this._state.go('app-dependency');

        }).catch(()=> {
            this._notification.error('获取服务依赖数据有误.');
        });


    }

    bulidTree(data){

        let item = {
             data:[],
             links:[]
        };
        let treeHead = [],treeParent = [],treeTail = [],linksHead = [],linksParent = [],linksTail = [],namesHead = [],namesParent = [],namesTail = [],names= [],children = [];
        let limit = parseInt(Math.pow(2,3.5))+1;
        function treeMakeUp(parentName,children){
            if(item.data.length==0){
                // 根节点
                treeParent = [{name:parentName,x:1,y:1}];
                item.data = [{name:parentName,x:1,y:1}];
                names = [parentName];
            }

            let parentIndex = names.length!=0?names.indexOf(parentName):0;
            treeHead = item.data.slice(0,parentIndex);
            treeParent = item.data.slice(parentIndex,parentIndex+1);
            treeTail = item.data.slice(parentIndex+1,item.data.length+1);

            linksHead = item.links.slice(0,parentIndex);
            linksParent = item.links.slice(parentIndex,parentIndex+1);
            linksTail = item.links.slice(parentIndex+1,item.data.length+1);

            namesHead = names.slice(0,parentIndex);
            namesParent = names.slice(parentIndex,parentIndex+1);
            namesTail = names.slice(parentIndex+1,item.data.length+1);

            let treeParentX = item.data[parentIndex].x;
            item.data[parentIndex].x = item.data[parentIndex].x + parseInt(children.length/2);

            for(let i=children.length-1;i>=0;i--){

                children[i].y = item.data[parentIndex].y +1;

                if(i % 2 == 0){

                    children[i].x = treeParentX + parseInt(i/2);
                    treeParent.unshift(angular.extend(children[i],children[i].dataStyle));
                    linksParent.unshift(angular.extend({source:parentName,target:children[i].name}, children[i].linkStyle));
                    namesParent.unshift(children[i].name);

                }else{

                    if(children.length%2 == 0){
                        children[i].x = treeParentX + (children.length - parseInt(i/2))
                    }else{
                        children[i].x = treeParentX + (children.length - parseInt(i/2)-1)
                    }

                    treeParent.push(angular.extend(children[i],children[i].dataStyle));
                    linksParent.push(angular.extend({source:parentName,target:children[i].name}, children[i].linkStyle))
                    namesParent.push(children[i].name);

                }
            }

            angular.forEach(treeTail, (ele,index) =>{
                if(treeTail[index].x == treeParentX){
                    treeTail[index].x = item.data[parentIndex].x;
                }else if(treeTail[index].x < treeParentX){
                    treeTail[index].x = treeTail[index].x;
                }else{
                    if(children.length % 2 == 0){
                        treeTail[index].x = children.length+treeTail[index].x;
                    }else{
                        treeTail[index].x = children.length+treeTail[index].x-1;
                    }
                }

            });

            item.data = treeHead.concat(treeParent,treeTail);
            item.links = linksHead.concat(linksParent,linksTail);
            names  = namesHead.concat(namesParent,namesTail);


        }
        function recursion(parent){
            if(parent.children && parent.children.length!=0){
                treeMakeUp(parent.name,parent.children);
                angular.forEach(parent.children,(ele,index)=>{
                    recursion(ele);
                })
            }
        }

        if(data[0].children.length==0){
            item.data = [{name:data[0].name,x:1,y:1}];
            this.rootNode = data[0];
        }else{
            recursion(data[0]);
        }


        if(limit >1){
            angular.forEach(item.data,function(ele,index){
                ele.y = (parseInt(item.data[item.data.length-1].x/limit)+1) *ele.y;
            })
        }

        setTimeout(()=>{
            this.config.series[0].data = item.data;
            this.config.series[0].links = item.links;
            this.model().setOption(this.config)
        },100)


    }


}
export default Create
